<?php
/**
 * 栖岛账号登录主类
 */
class Qidao_Connect {
    /**
     * 插件选项
     */
    private $options;

    /**
     * 构造函数
     */
    public function __construct() {
        $this->options = get_option('qidao_connect_options', array());
    }

    /**
     * 初始化插件
     */
    public function init() {
        // 加载文本域
        load_plugin_textdomain('qidao-connect', false, dirname(QIDAO_CONNECT_BASENAME) . '/languages');
        
        // 添加设置页面
        add_action('admin_menu', array($this, 'add_settings_page'));
        add_action('admin_init', array($this, 'register_settings'));
        
        // 添加登录按钮
        add_action('login_form', array($this, 'add_login_button'));
        add_action('login_enqueue_scripts', array($this, 'enqueue_login_styles'));
        
        // 添加个人资料字段
        add_action('show_user_profile', array($this, 'add_profile_fields'));
        add_action('edit_user_profile', array($this, 'add_profile_fields'));
        
        // 注册路由
        add_action('init', array($this, 'register_routes'));
        add_filter('query_vars', array($this, 'add_query_vars'));
        add_action('parse_request', array($this, 'parse_request'));
        
        // 添加登录小工具
        add_action('widgets_init', array($this, 'register_widgets'));
        
        // 添加短代码
        add_shortcode('qidao_login', array($this, 'login_shortcode'));
        
        // 处理qidao_auth参数，用于自动进入管理界面
        add_action('init', array($this, 'handle_admin_auth'));
    }
    
    /**
     * 处理管理界面认证
     */
    public function handle_admin_auth() {
        // 获取调试日志路径
        $debug_log = plugin_dir_path(dirname(__FILE__)) . 'qidao_debug.log';
        
        // 检查是否有认证参数
        if (isset($_GET['qidao_auth'])) {
            $nonce = $_GET['qidao_auth'];
            
            // 验证nonce
            if (wp_verify_nonce($nonce, 'access-wp-admin')) {
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 检测到有效的管理界面认证请求\n", FILE_APPEND);
                
                // 确保用户已登录
                if (is_user_logged_in()) {
                    $user = wp_get_current_user();
                    file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户已登录: {$user->ID} ({$user->user_login})\n", FILE_APPEND);
                    
                    // 设置管理员会话cookie
                    $cookie_name = 'wp-settings-' . $user->ID;
                    if (!isset($_COOKIE[$cookie_name])) {
                        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 设置管理员会话cookie: {$cookie_name}\n", FILE_APPEND);
                        setcookie($cookie_name, 'libraryContent=browse&editor=tinymce', time() + 3600 * 24 * 30, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
                    }
                    
                    // 强制刷新认证
                    wp_set_auth_cookie($user->ID, true, is_ssl());
                    
                    // 去掉URL中的nonce参数，重定向到干净的管理界面URL
                    $admin_url = remove_query_arg('qidao_auth', admin_url());
                    file_put_contents($debug_log, date('Y-m-d H:i:s') . " 重定向到干净的管理界面URL: {$admin_url}\n", FILE_APPEND);
                    
                    wp_redirect($admin_url);
                    exit;
                } else {
                    file_put_contents($debug_log, date('Y-m-d H:i:s') . " 错误: 认证请求有效，但用户未登录\n", FILE_APPEND);
                }
            } else {
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 警告: 无效的管理界面认证请求\n", FILE_APPEND);
            }
        }
    }
    
    /**
     * 添加设置页面
     */
    public function add_settings_page() {
        add_options_page(
            __('栖岛账号登录设置', 'qidao-connect'),
            __('栖岛账号登录', 'qidao-connect'),
            'manage_options',
            'qidao-connect',
            array($this, 'render_settings_page')
        );
    }
    
    /**
     * 渲染设置页面
     */
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <?php
            // 处理重写规则刷新请求
            if (isset($_GET['qidao_flush_rules']) && $_GET['qidao_flush_rules'] === '1' && check_admin_referer('qidao_flush_rules')) {
                // 添加重写规则
                add_rewrite_rule('^qidao-oauth/?$', 'index.php?qidao_action=oauth', 'top');
                add_rewrite_rule('^qidao-callback/?$', 'index.php?qidao_action=callback', 'top');
                
                // 刷新重写规则
                flush_rewrite_rules();
                
                echo '<div class="notice notice-success is-dismissible"><p>' . __('重写规则已刷新！', 'qidao-connect') . '</p></div>';
            }
            ?>
            
            <div style="margin: 15px 0; padding: 10px; background-color: #f8f9fa; border-left: 4px solid #6cf;">
                <p>还没有栖岛账号？<a href="https://open.tvcloud.top/admin/register.php" target="_blank" style="color: #0088cc; text-decoration: underline;">点击这里</a> 前往栖岛平台注册账号。</p>
                <p>注册后，您需要创建应用并获取应用ID和密钥。</p>
            </div>
            
            <form action="options.php" method="post">
                <?php
                settings_fields('qidao_connect_options');
                do_settings_sections('qidao-connect');
                submit_button();
                ?>
            </form>
            
            <div class="card" style="max-width: 100%;">
                <h2><?php _e('故障排除', 'qidao-connect'); ?></h2>
                <p><?php _e('如果登录按钮链接返回404错误，请尝试刷新重写规则：', 'qidao-connect'); ?></p>
                <p>
                    <a href="<?php echo wp_nonce_url(add_query_arg('qidao_flush_rules', '1'), 'qidao_flush_rules'); ?>" class="button button-secondary">
                        <?php _e('刷新重写规则', 'qidao-connect'); ?>
                    </a>
                </p>
                <p><?php _e('注意：插件现在默认使用查询参数方式生成链接，不依赖于重写规则，因此即使重写规则不生效，登录功能也应该正常工作。', 'qidao-connect'); ?></p>
            </div>
            
            <div style="margin-top: 20px; padding: 10px; background-color: #f8f9fa; border-top: 1px solid #ddd;">
                <p>栖岛账号登录插件 v<?php echo QIDAO_CONNECT_VERSION; ?> | 开发者：艺当然</p>
                <p>如有问题，请联系开发者或访问 <a href="https://web.tvcloud.top/" target="_blank">栖岛平台</a></p>
                <p>版权所有 © 2023-2024 艺当然，保留所有权利</p>
            </div>
        </div>
        <?php
    }
    
    /**
     * 注册设置
     */
    public function register_settings() {
        register_setting(
            'qidao_connect_options',
            'qidao_connect_options',
            array($this, 'validate_options')
        );
        
        add_settings_section(
            'qidao_connect_main',
            __('基本设置', 'qidao-connect'),
            array($this, 'section_main_callback'),
            'qidao-connect'
        );
        
        add_settings_field(
            'app_id',
            __('应用ID (Client ID)', 'qidao-connect'),
            array($this, 'field_app_id_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'app_secret',
            __('应用密钥 (Client Secret)', 'qidao-connect'),
            array($this, 'field_app_secret_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'callback',
            __('回调地址', 'qidao-connect'),
            array($this, 'field_callback_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'scope',
            __('授权域 (Scope)', 'qidao-connect'),
            array($this, 'field_scope_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'custom',
            __('是否需要完善资料', 'qidao-connect'),
            array($this, 'field_custom_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'default_role',
            __('默认用户角色', 'qidao-connect'),
            array($this, 'field_default_role_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        add_settings_field(
            'privilege_emails',
            __('特权邮箱列表', 'qidao-connect'),
            array($this, 'field_privilege_emails_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
        
        // 添加登录后重定向选项
        add_settings_field(
            'redirect_after_login',
            __('登录后重定向URL', 'qidao-connect'),
            array($this, 'field_redirect_after_login_callback'),
            'qidao-connect',
            'qidao_connect_main'
        );
    }
    
    /**
     * 主设置区域回调
     */
    public function section_main_callback() {
        echo '<p>' . __('配置栖岛账号登录所需的基本信息', 'qidao-connect') . '</p>';
    }
    
    /**
     * 应用ID字段回调
     */
    public function field_app_id_callback() {
        $app_id = isset($this->options['app_id']) ? $this->options['app_id'] : '';
        echo '<input type="text" id="app_id" name="qidao_connect_options[app_id]" value="' . esc_attr($app_id) . '" class="regular-text" />';
        echo '<p class="description">' . __('栖岛开放平台申请的应用ID', 'qidao-connect') . '</p>';
    }
    
    /**
     * 应用密钥字段回调
     */
    public function field_app_secret_callback() {
        $app_secret = isset($this->options['app_secret']) ? $this->options['app_secret'] : '';
        echo '<input type="text" id="app_secret" name="qidao_connect_options[app_secret]" value="' . esc_attr($app_secret) . '" class="regular-text" />';
        echo '<p class="description">' . __('栖岛开放平台申请的应用密钥', 'qidao-connect') . '</p>';
    }
    
    /**
     * 回调地址字段回调
     */
    public function field_callback_callback() {
        $callback = site_url('?qidao_action=callback');
        echo '<input type="text" id="callback" value="' . esc_attr($callback) . '" class="regular-text" readonly />';
        echo '<p class="description">' . __('请将此地址设置到栖岛开放平台的回调域中', 'qidao-connect') . '</p>';
    }
    
    /**
     * 授权域字段回调
     */
    public function field_scope_callback() {
        $scope = isset($this->options['scope']) ? $this->options['scope'] : 'email screen_name avatar url';
        echo '<input type="text" id="scope" name="qidao_connect_options[scope]" value="' . esc_attr($scope) . '" class="regular-text" />';
        echo '<p class="description">' . __('授权域，多个权限用空格分隔，例如：profile email user_name screen_name avatar url', 'qidao-connect') . '</p>';
    }
    
    /**
     * 是否需要完善资料字段回调
     */
    public function field_custom_callback() {
        $custom = isset($this->options['custom']) ? $this->options['custom'] : 0;
        echo '<label><input type="radio" name="qidao_connect_options[custom]" value="1" ' . checked(1, $custom, false) . ' /> ' . __('是', 'qidao-connect') . '</label> ';
        echo '<label><input type="radio" name="qidao_connect_options[custom]" value="0" ' . checked(0, $custom, false) . ' /> ' . __('否', 'qidao-connect') . '</label>';
        echo '<p class="description">' . __('用户使用栖岛账号登录后，是否需要完善昵称、邮箱等信息；选择不需要完善资料则直接使用获取到的昵称。', 'qidao-connect') . '</p>';
    }
    
    /**
     * 默认用户角色字段回调
     */
    public function field_default_role_callback() {
        $default_role = isset($this->options['default_role']) ? $this->options['default_role'] : 'subscriber';
        $roles = wp_roles()->get_names();
        echo '<select id="default_role" name="qidao_connect_options[default_role]">';
        foreach ($roles as $role => $name) {
            echo '<option value="' . esc_attr($role) . '" ' . selected($role, $default_role, false) . '>' . esc_html($name) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . __('栖岛用户登录后默认的用户角色', 'qidao-connect') . '</p>';
    }
    
    /**
     * 特权邮箱列表字段回调
     */
    public function field_privilege_emails_callback() {
        $privilege_emails = isset($this->options['privilege_emails']) ? $this->options['privilege_emails'] : '';
        echo '<textarea id="privilege_emails" name="qidao_connect_options[privilege_emails]" rows="5" cols="50" class="large-text">' . esc_textarea($privilege_emails) . '</textarea>';
        echo '<p class="description">' . __('这些邮箱的栖岛用户将获得管理员权限，一行一个邮箱', 'qidao-connect') . '</p>';
    }
    
    /**
     * 登录后重定向URL字段回调
     */
    public function field_redirect_after_login_callback() {
        $redirect_after_login = isset($this->options['redirect_after_login']) ? $this->options['redirect_after_login'] : '';
        echo '<input type="text" id="redirect_after_login" name="qidao_connect_options[redirect_after_login]" value="' . esc_attr($redirect_after_login) . '" class="regular-text" />';
        echo '<p class="description">' . __('用户登录成功后，将重定向到此URL。留空则使用默认重定向。', 'qidao-connect') . '</p>';
    }
    
    /**
     * 验证选项
     */
    public function validate_options($input) {
        $output = array();
        
        $output['app_id'] = sanitize_text_field($input['app_id']);
        $output['app_secret'] = sanitize_text_field($input['app_secret']);
        $output['scope'] = sanitize_text_field($input['scope']);
        $output['custom'] = absint($input['custom']);
        $output['default_role'] = sanitize_text_field($input['default_role']);
        $output['privilege_emails'] = sanitize_textarea_field($input['privilege_emails']);
        $output['redirect_after_login'] = esc_url_raw($input['redirect_after_login']); // 验证重定向URL
        
        return $output;
    }
    
    /**
     * 在登录表单中添加登录按钮
     */
    public function add_login_button() {
        if (empty($this->options['app_id'])) {
            return;
        }
        
        echo '<div class="qidao-login">';
        echo '<div class="qidao-login-title">' . __('使用栖岛账号快速登录', 'qidao-connect') . '</div>';
        echo '<div class="qidao-login-btn">' . $this->login_button() . '</div>';
        echo '</div>';
    }
    
    /**
     * 加载登录页面样式
     */
    public function enqueue_login_styles() {
        wp_enqueue_style('qidao-connect-login', QIDAO_CONNECT_URL . 'assets/css/login.css', array(), QIDAO_CONNECT_VERSION);
    }
    
    /**
     * 生成登录按钮
     */
    public function login_button($text = false) {
        if (empty($this->options['app_id'])) {
            return '';
        }
        
        // 使用查询参数方式，不依赖重写规则
        $url = add_query_arg('qidao_action', 'oauth', home_url('/'));
        
        if ($text) {
            // 文本样式
            return '<a href="' . esc_url($url) . '" title="' . __('栖岛登录', 'qidao-connect') . '">' . __('栖岛登录', 'qidao-connect') . '</a>';
        } else {
            // 按钮样式
            $icon_path = QIDAO_CONNECT_PATH . 'assets/images/qidao.png';
            $icon_url = file_exists($icon_path) 
                ? QIDAO_CONNECT_URL . 'assets/images/qidao.png' 
                : QIDAO_CONNECT_URL . 'assets/images/qidao.svg';
            
            return '<a href="' . esc_url($url) . '"><img src="' . esc_url($icon_url) . '" alt="' . __('栖岛登录', 'qidao-connect') . '"></a>';
        }
    }
    
    /**
     * 添加个人资料字段
     */
    public function add_profile_fields($user) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'qidao_connect';
        $qidao_user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d", $user->ID));
        
        if ($qidao_user) {
            ?>
            <h3><?php _e('栖岛账号信息', 'qidao-connect'); ?></h3>
            <table class="form-table">
                <tr>
                    <th><label><?php _e('栖岛昵称', 'qidao-connect'); ?></label></th>
                    <td><?php echo esc_html($qidao_user->nickname); ?></td>
                </tr>
                <tr>
                    <th><label><?php _e('栖岛头像', 'qidao-connect'); ?></label></th>
                    <td><img src="<?php echo esc_url($qidao_user->head_img); ?>" style="width: 50px; height: 50px; border-radius: 50%;" /></td>
                </tr>
                <tr>
                    <th><label><?php _e('绑定时间', 'qidao-connect'); ?></label></th>
                    <td><?php echo esc_html($qidao_user->datetime); ?></td>
                </tr>
            </table>
            <?php
        }
    }
    
    /**
     * 注册路由
     */
    public function register_routes() {
        // 添加重写规则
        add_rewrite_rule('^qidao-oauth/?$', 'index.php?qidao_action=oauth', 'top');
        add_rewrite_rule('^qidao-callback/?$', 'index.php?qidao_action=callback', 'top');
        
        // 检查规则是否存在，如果不存在则刷新
        global $wp_rewrite;
        $rules = get_option('rewrite_rules');
        
        if (!isset($rules['^qidao-oauth/?$']) || !isset($rules['^qidao-callback/?$'])) {
            // 如果规则不存在，尝试手动添加到规则数组
            if (!isset($wp_rewrite->extra_rules_top['^qidao-oauth/?$'])) {
                $wp_rewrite->extra_rules_top['^qidao-oauth/?$'] = 'index.php?qidao_action=oauth';
            }
            
            if (!isset($wp_rewrite->extra_rules_top['^qidao-callback/?$'])) {
                $wp_rewrite->extra_rules_top['^qidao-callback/?$'] = 'index.php?qidao_action=callback';
            }
            
            // 刷新重写规则
            flush_rewrite_rules();
            
            // 记录日志
            error_log('QidaoConnect: 重写规则已刷新');
        }
    }
    
    /**
     * 添加查询变量
     */
    public function add_query_vars($vars) {
        $vars[] = 'qidao_action';
        return $vars;
    }
    
    /**
     * 解析请求
     */
    public function parse_request($wp) {
        // 首先检查查询参数（更可靠的方式）
        if (isset($_GET['qidao_action'])) {
            $action = $_GET['qidao_action'];
            
            if ($action === 'oauth') {
                $this->handle_oauth();
                exit;
            } elseif ($action === 'callback') {
                $this->handle_callback();
                exit;
            }
        }
        
        // 然后检查查询变量（重写规则方式）
        if (isset($wp->query_vars['qidao_action'])) {
            $action = $wp->query_vars['qidao_action'];
            
            if ($action === 'oauth') {
                $this->handle_oauth();
                exit;
            } elseif ($action === 'callback') {
                $this->handle_callback();
                exit;
            }
        }
    }
    
    /**
     * 处理OAuth请求
     */
    private function handle_oauth() {
        if (empty($this->options['app_id']) || empty($this->options['app_secret'])) {
            wp_die(__('栖岛账号登录未正确配置，请联系网站管理员。', 'qidao-connect'));
        }
        
        // 生成随机state参数
        $state = md5(uniqid(rand(), true));
        setcookie('qidao_state', $state, time() + 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        
        // 修改：确保回调URL始终可用，无论重写规则是否正常工作
        $redirect_uri = site_url('?qidao_action=callback');
        
        // 构建授权URL - 使用栖岛OAuth2授权端点
        $scope = isset($this->options['scope']) ? $this->options['scope'] : 'email screen_name avatar url';
        
        $auth_url = 'https://api.qidao.tvcloud.top/oauth2/authorize?' . http_build_query(array(
            'client_id' => $this->options['app_id'],
            'redirect_uri' => $redirect_uri,
            'response_type' => 'code',
            'scope' => $scope,
            'state' => $state
        ));
        
        // 重定向到授权页面
        wp_redirect($auth_url);
        exit;
    }
    
    /**
     * 处理回调请求
     */
    private function handle_callback() {
        if (empty($_GET['code'])) {
            wp_die(__('授权请求缺少必要参数。', 'qidao-connect'));
        }
        
        // 验证state参数
        if (!isset($_COOKIE['qidao_state']) || $_COOKIE['qidao_state'] !== $_GET['state']) {
            wp_die(__('安全验证失败，请重新尝试登录。', 'qidao-connect'));
        }
        
        // 清除state cookie
        setcookie('qidao_state', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        
        // 获取access token
        $code = $_GET['code'];
        // 修改：确保回调URL与授权请求中使用的完全一致
        $redirect_uri = site_url('?qidao_action=callback');
        
        // 使用栖岛OAuth2令牌端点
        $token_url = 'https://api.qidao.tvcloud.top/oauth2/token';
        $response = wp_remote_post($token_url, array(
            'body' => array(
                'grant_type' => 'authorization_code',
                'client_id' => $this->options['app_id'],
                'client_secret' => $this->options['app_secret'],
                'code' => $code,
                'redirect_uri' => $redirect_uri
            )
        ));
        
        if (is_wp_error($response)) {
            wp_die(__('获取访问令牌失败：', 'qidao-connect') . $response->get_error_message());
        }
        
        $token_data = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($token_data['error'])) {
            wp_die(__('获取访问令牌失败：', 'qidao-connect') . $token_data['error_description']);
        }
        
        // 创建调试日志目录
        $debug_dir = plugin_dir_path(dirname(__FILE__));
        $debug_log = $debug_dir . 'qidao_debug.log';
        
        // 获取用户信息 - 使用栖岛OAuth2用户信息端点
        $user_url = 'https://api.qidao.tvcloud.top/oauth2/userinfo/oauth';
        
        // 记录调试信息
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 开始获取用户信息\n", FILE_APPEND);
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 令牌数据: " . print_r($token_data, true) . "\n", FILE_APPEND);
        
        // 请求用户信息
        $user_url_with_token = add_query_arg('access_token', $token_data['access_token'], $user_url);
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 请求URL: " . $user_url_with_token . "\n", FILE_APPEND);
        
        // 使用GET请求获取用户数据
        $user_response = wp_remote_get($user_url_with_token);
        
        // 记录响应信息
        $response_code = wp_remote_retrieve_response_code($user_response);
        $response_body = wp_remote_retrieve_body($user_response);
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " API响应状态码: {$response_code}\n", FILE_APPEND);
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " API响应内容: {$response_body}\n", FILE_APPEND);
        
        if (is_wp_error($user_response)) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 获取用户信息失败: " . $user_response->get_error_message() . "\n", FILE_APPEND);
            
            // 备用方法: 使用Authorization头获取用户信息
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 尝试使用Authorization头获取用户信息\n", FILE_APPEND);
            $user_response = wp_remote_get($user_url, array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $token_data['access_token']
                )
            ));
            
            if (is_wp_error($user_response)) {
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 备用方法也失败: " . $user_response->get_error_message() . "\n", FILE_APPEND);
                wp_die(__('获取栖岛用户信息失败：', 'qidao-connect') . $user_response->get_error_message());
            }
            
            $response_code = wp_remote_retrieve_response_code($user_response);
            $response_body = wp_remote_retrieve_body($user_response);
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 备用方法响应状态码: {$response_code}\n", FILE_APPEND);
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 备用方法响应内容: {$response_body}\n", FILE_APPEND);
        }
        
        // 解析用户数据
        $user_data = json_decode($response_body, true);
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 解析后的用户数据: " . print_r($user_data, true) . "\n", FILE_APPEND);
        
        // 检查响应格式
        if (!$user_data) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 无法解析响应JSON\n", FILE_APPEND);
            wp_die(__('获取栖岛用户信息失败：响应格式无效', 'qidao-connect'));
        }
        
        // 检查是否有错误状态码
        if (isset($user_data['status']) && $user_data['status'] >= 400) {
            $error_msg = isset($user_data['message']) ? $user_data['message'] : '未知错误';
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " API返回HTTP错误: {$user_data['status']} - {$error_msg}\n", FILE_APPEND);
            wp_die(__('获取栖岛用户信息失败：', 'qidao-connect') . $error_msg);
        }
        
        if (isset($user_data['code']) && $user_data['code'] == 1 && isset($user_data['data'])) {
            // 正确的响应格式
            $user_info = $user_data['data'];
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 成功获取用户信息: " . print_r($user_info, true) . "\n", FILE_APPEND);
        } else {
            // 检查是否有其他格式的成功响应
            if (isset($user_data['uid']) || isset($user_data['id'])) {
                // 直接使用顶层数据
                $user_info = $user_data;
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 使用顶层用户数据: " . print_r($user_info, true) . "\n", FILE_APPEND);
            } else {
                // 错误响应
                $error_msg = isset($user_data['msg']) ? $user_data['msg'] : 
                          (isset($user_data['error_description']) ? $user_data['error_description'] : '未知错误');
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " API返回错误: {$error_msg}\n", FILE_APPEND);
                
                wp_die(__('获取栖岛用户信息失败：', 'qidao-connect') . $error_msg);
            }
        }
        
        // 处理登录或注册
        $this->process_login($user_info, $token_data);
    }
    
    /**
     * 处理登录或注册
     */
    private function process_login($user_data, $token_data) {
        // 处理登录和重定向
        $this->do_login_and_redirect($user_data, $token_data);
    }
    
    /**
     * 处理登录和重定向
     */
    private function do_login_and_redirect($user_data, $token_data) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'qidao_connect';
        
        // 获取调试日志路径
        $debug_log = plugin_dir_path(dirname(__FILE__)) . 'qidao_debug.log';
        
        // 提取用户信息，支持多种字段命名
        $uid = '';
        if (isset($user_data['uid'])) {
            $uid = $user_data['uid'];
        } elseif (isset($user_data['id'])) {
            $uid = $user_data['id'];
        } elseif (isset($user_data['user_id'])) {
            $uid = $user_data['user_id'];
        }
        
        if (empty($uid)) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 错误: 用户数据中缺少uid/id/user_id\n", FILE_APPEND);
            wp_die(__('获取栖岛用户信息失败: 用户ID不存在', 'qidao-connect'));
        }
        
        $name = isset($user_data['name']) ? $user_data['name'] : 
               (isset($user_data['username']) ? $user_data['username'] : '');
        
        $screenName = isset($user_data['screenName']) ? $user_data['screenName'] : 
                     (isset($user_data['screen_name']) ? $user_data['screen_name'] : 
                     (isset($user_data['nickname']) ? $user_data['nickname'] : $name));
        
        $email = isset($user_data['mail']) ? $user_data['mail'] : 
               (isset($user_data['email']) ? $user_data['email'] : '');
        
        $avatar = isset($user_data['avatar']) ? $user_data['avatar'] : 
                (isset($user_data['avatarUrl']) ? $user_data['avatarUrl'] : 
                (isset($user_data['head_img']) ? $user_data['head_img'] : ''));
        
        $url = isset($user_data['url']) ? $user_data['url'] : 
             (isset($user_data['website']) ? $user_data['website'] : '');
        
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 提取的用户信息: uid={$uid}, name={$name}, screenName={$screenName}, email={$email}\n", FILE_APPEND);
        
        // 处理用户登录或注册
        $user_id = $this->get_or_create_user($uid, $name, $screenName, $email, $avatar, $url, $token_data);
        
        if ($user_id > 0) {
            // 登录用户（使用核心API，但不通过标准的过滤器）
            $this->custom_set_auth($user_id);
            
            // 直接重定向到WordPress后台
            $this->direct_redirect();
        } else {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 错误: 无法确定用户ID\n", FILE_APPEND);
            wp_die(__('登录失败：无法确定用户身份', 'qidao-connect'));
        }
    }
    
    /**
     * 获取或创建用户
     */
    private function get_or_create_user($uid, $name, $screenName, $email, $avatar, $url, $token_data) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'qidao_connect';
        $debug_log = plugin_dir_path(dirname(__FILE__)) . 'qidao_debug.log';
        
        // 检查是否已经有关联的用户
        $qidao_user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE openid = %s", $uid));
        
        if ($qidao_user) {
            // 已存在关联用户，更新令牌信息
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 找到已关联的WordPress用户ID: {$qidao_user->user_id}\n", FILE_APPEND);
            
            $wpdb->update(
                $table_name,
                array(
                    'access_token' => $token_data['access_token'],
                    'refresh_token' => isset($token_data['refresh_token']) ? $token_data['refresh_token'] : '',
                    'expires_in' => isset($token_data['expires_in']) ? $token_data['expires_in'] : 0,
                    'datetime' => current_time('mysql'),
                    'name' => $name,
                    'nickname' => $screenName,
                    'head_img' => $avatar
                ),
                array('id' => $qidao_user->id)
            );
            
            return $qidao_user->user_id;
        }
        
        // 尝试通过邮箱查找用户
        if (!empty($email)) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 尝试通过邮箱查找用户: {$email}\n", FILE_APPEND);
            $user = get_user_by('email', $email);
            if ($user) {
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 找到邮箱相同的用户ID: {$user->ID}\n", FILE_APPEND);
                
                // 存在相同邮箱的用户，绑定账号
                $wpdb->insert(
                    $table_name,
                    array(
                        'user_id' => $user->ID,
                        'openid' => $uid,
                        'access_token' => $token_data['access_token'],
                        'refresh_token' => isset($token_data['refresh_token']) ? $token_data['refresh_token'] : '',
                        'expires_in' => isset($token_data['expires_in']) ? $token_data['expires_in'] : 0,
                        'datetime' => current_time('mysql'),
                        'name' => $name,
                        'nickname' => $screenName,
                        'gender' => 0,
                        'head_img' => $avatar
                    )
                );
                
                return $user->ID;
            }
        }
        
        // 创建新用户
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 没有找到匹配的用户，准备创建新用户\n", FILE_APPEND);
        $username = 'qidao_' . $uid;
        $user_email = !empty($email) ? $email : $username . '@example.com';
        $display_name = !empty($screenName) ? $screenName : $username;
        
        // 检查用户名是否已存在
        if (username_exists($username)) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户名已存在，生成唯一用户名\n", FILE_APPEND);
            $username = $username . '_' . substr(md5(uniqid(rand(), true)), 0, 6);
        }
        
        // 创建随机密码
        $password = wp_generate_password(12, false);
        
        // 确定用户角色
        $role = isset($this->options['default_role']) ? $this->options['default_role'] : 'subscriber';
        
        // 检查是否为特权邮箱
        if (!empty($email) && !empty($this->options['privilege_emails'])) {
            $privilege_emails = explode("\n", $this->options['privilege_emails']);
            $privilege_emails = array_map('trim', $privilege_emails);
            
            if (in_array($email, $privilege_emails)) {
                $role = 'administrator';
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 特权邮箱，设置角色为管理员\n", FILE_APPEND);
            }
        }
        
        // 创建用户
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 创建新用户: username={$username}, email={$user_email}, role={$role}\n", FILE_APPEND);
        $user_id = wp_create_user($username, $password, $user_email);
        
        if (is_wp_error($user_id)) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 创建用户失败: " . $user_id->get_error_message() . "\n", FILE_APPEND);
            return 0;
        }
        
        // 更新用户信息
        $user_data_update = array(
            'ID' => $user_id,
            'display_name' => $display_name,
            'nickname' => $display_name,
            'role' => $role
        );
        
        // 如果有网站URL，也更新
        if (!empty($url)) {
            $user_data_update['user_url'] = $url;
        }
        
        wp_update_user($user_data_update);
        
        // 保存栖岛用户信息
        $wpdb->insert(
            $table_name,
            array(
                'user_id' => $user_id,
                'openid' => $uid,
                'access_token' => $token_data['access_token'],
                'refresh_token' => isset($token_data['refresh_token']) ? $token_data['refresh_token'] : '',
                'expires_in' => isset($token_data['expires_in']) ? $token_data['expires_in'] : 0,
                'datetime' => current_time('mysql'),
                'name' => $name,
                'nickname' => $screenName,
                'gender' => 0,
                'head_img' => $avatar
            )
        );
        
        return $user_id;
    }
    
    /**
     * 自定义设置认证（绕过WordPress过滤器）
     */
    private function custom_set_auth($user_id) {
        $debug_log = plugin_dir_path(dirname(__FILE__)) . 'qidao_debug.log';
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 开始设置用户{$user_id}的认证\n", FILE_APPEND);
        
        // 获取用户
        $user = get_user_by('ID', $user_id);
        if (!$user) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 错误: 找不到用户ID: {$user_id}\n", FILE_APPEND);
            return;
        }
        
        // 记录用户数据
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户数据: " . print_r($user->data, true) . "\n", FILE_APPEND);
        
        // 清除现有auth cookie
        wp_clear_auth_cookie();
        
        // 获取用户可访问的角色列表
        $user_roles = $user->roles;
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户角色: " . print_r($user_roles, true) . "\n", FILE_APPEND);
        
        // 确保用户有访问后台的能力
        $user_cap = $user->get_role_caps();
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户权限: " . print_r($user_cap, true) . "\n", FILE_APPEND);
        
        // 设置全局用户变量
        wp_set_current_user($user_id);
        
        // 设置认证cookie
        wp_set_auth_cookie($user_id, true, is_ssl());
        
        // 执行登录动作
        do_action('wp_login', $user->user_login, $user);
        
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 完成认证设置\n", FILE_APPEND);
    }
    
    /**
     * 直接重定向，不经过WordPress过滤器
     */
    private function direct_redirect() {
        $debug_log = plugin_dir_path(dirname(__FILE__)) . 'qidao_debug.log';
        
        // 获取当前登录用户
        $current_user = wp_get_current_user();
        $user_id = $current_user->ID;
        $user_login = $current_user->user_login;
        
        // 检查用户是否已成功登录
        if ($user_id > 0) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 用户已登录: {$user_id} ({$user_login})\n", FILE_APPEND);
        } else {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 警告: 用户登录状态检查失败\n", FILE_APPEND);
        }
        
        // 构建安全的后台URL
        $admin_nonce = wp_create_nonce('access-wp-admin');
        $redirect_url = add_query_arg('qidao_auth', $admin_nonce, admin_url());
        
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 准备重定向到: {$redirect_url}\n", FILE_APPEND);
        
        // 立即终止所有输出缓冲
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // 禁用所有可能干扰重定向的过滤器
        global $wp_filter;
        if (isset($wp_filter['login_redirect'])) unset($wp_filter['login_redirect']);
        if (isset($wp_filter['wp_redirect'])) unset($wp_filter['wp_redirect']);
        if (isset($wp_filter['auth_redirect'])) unset($wp_filter['auth_redirect']);
        if (isset($wp_filter['auth_redirect_scheme'])) unset($wp_filter['auth_redirect_scheme']);
        
        // 确保在执行重定向前存储所有会话和cookie数据
        if (function_exists('session_write_close')) {
            @session_write_close();
        }
        
        // 检查认证cookie是否已设置
        $auth_cookie_set = false;
        foreach ($_COOKIE as $name => $value) {
            if (strpos($name, 'wordpress_logged_in_') === 0) {
                $auth_cookie_set = true;
                file_put_contents($debug_log, date('Y-m-d H:i:s') . " 检测到认证cookie: {$name}\n", FILE_APPEND);
                break;
            }
        }
        
        if (!$auth_cookie_set) {
            file_put_contents($debug_log, date('Y-m-d H:i:s') . " 警告: 未检测到认证cookie\n", FILE_APPEND);
        }
        
        // 直接输出JavaScript重定向，避免使用任何WordPress函数
        echo '<!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>栖岛登录成功</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <script type="text/javascript">
                window.onload = function() {
                    document.cookie = "wordpress_test_cookie=WP Cookie check; path=/";
                    
                    // 启动倒计时
                    var count = 3;
                    var countElem = document.getElementById("countdown");
                    var timer = setInterval(function() {
                        count--;
                        countElem.innerHTML = count;
                        if (count <= 0) {
                            clearInterval(timer);
                            window.location.replace("' . esc_url($redirect_url) . '");
                        }
                    }, 1000);
                }
            </script>
            <meta http-equiv="refresh" content="3;url=' . esc_url($redirect_url) . '">
            <style>
               body {
                   font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                   background-color: #f0f2f5;
                   margin: 0;
                   padding: 0;
                   display: flex;
                   justify-content: center;
                   align-items: center;
                   min-height: 100vh;
                   color: #333;
               }
               .login-container {
                   background-color: #fff;
                   border-radius: 8px;
                   box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
                   padding: 30px 40px;
                   text-align: center;
                   max-width: 90%;
                   width: 420px;
               }
               .success-icon {
                   width: 70px;
                   height: 70px;
                   border-radius: 50%;
                   background-color: #4CAF50;
                   color: white;
                   display: flex;
                   justify-content: center;
                   align-items: center;
                   margin: 0 auto 20px;
                   font-size: 40px;
                   font-weight: bold;
               }
               h1 {
                   font-size: 24px;
                   margin: 20px 0;
                   font-weight: 500;
               }
               p {
                   font-size: 16px;
                   line-height: 1.5;
                   color: #666;
                   margin-bottom: 20px;
               }
               .countdown {
                   font-size: 18px;
                   font-weight: bold;
                   color: #4CAF50;
                   margin: 15px 0;
               }
               .manual-link {
                   display: inline-block;
                   margin-top: 15px;
                   color: #2196F3;
                   text-decoration: none;
                   font-weight: 500;
                   padding: 10px 15px;
                   border: 1px solid #2196F3;
                   border-radius: 4px;
                   transition: all 0.3s ease;
               }
               .manual-link:hover {
                   background-color: #2196F3;
                   color: #fff;
               }
               .logo {
                   margin-bottom: 20px;
                   max-width: 150px;
               }
               @media (max-width: 480px) {
                   .login-container {
                       padding: 20px;
                       width: 90%;
                   }
               }
            </style>
        </head>
        <body>
            <div class="login-container">
                <div class="success-icon">✓</div>
                <h1>登录成功</h1>
                <p>栖岛账号授权成功，即将进入管理后台</p>
                <div class="countdown"><span id="countdown">3</span> 秒后自动跳转</div>
                <a href="' . esc_url($redirect_url) . '" class="manual-link">立即进入</a>
            </div>
        </body>
        </html>';
        
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " 已执行重定向输出\n", FILE_APPEND);
        exit;
    }
    
    /**
     * 注册小工具
     */
    public function register_widgets() {
        require_once QIDAO_CONNECT_PATH . 'includes/class-qidao-connect-widget.php';
        register_widget('Qidao_Connect_Widget');
    }
    
    /**
     * 登录短代码
     */
    public function login_shortcode($atts) {
        $atts = shortcode_atts(array(
            'text' => false,
        ), $atts, 'qidao_login');
        
        $text = filter_var($atts['text'], FILTER_VALIDATE_BOOLEAN);
        
        ob_start();
        echo '<div class="qidao-connect-shortcode">';
        echo $this->login_button($text);
        echo '</div>';
        return ob_get_clean();
    }
} 